<template>
  <div class="">
    <el-form ref="valueMapper" :model="valueMapper" label-width="150px" size="mini">
      <el-form-item label="步骤名称" prop="name">
        <el-input v-model="valueMapper.name"></el-input>
      </el-form-item>
      <el-form-item label="使用字段名" prop="field_to_use">
        <el-select v-model="valueMapper.field_to_use" placeholder="请选择" style="width:100%">
          <el-option
            v-for="item in fieldOptions"
            :key="item.name"
            :label="item.name"
            :value="item.name">
          </el-option>
        </el-select>
      </el-form-item>
       <el-form-item label="目标字段名(空=覆盖)" prop="target_field">
         <el-input v-model="valueMapper.target_field"></el-input>
      </el-form-item>
       <el-form-item label="不匹配时默认值" prop="non_match_default">
         <el-input v-model="valueMapper.non_match_default"></el-input>
      </el-form-item>
      <div class="box" title="字段值" style="margin-top:20px;">
        <el-row>
          <el-col :span="24">
            <el-table :data="valueMapper.fields" border style="width: 100%;" size="mini" height="200" v-loading="dataListLoading">
              <el-table-column label="操作" width="80" :resizable=false>
                <template slot-scope="scope">
                  <div class="optionStyle">
                    <el-button
                        type="text"
                        @click="removeObj(scope.$index)"
                        size="mini">移除
                    </el-button>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="source_value" label="源值">
                <template slot-scope="scope">
                  <el-input size="mini" v-model="scope.row.source_value"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="target_value" label="目标值">
                <template slot-scope="scope">
                  <el-input size="mini" v-model="scope.row.target_value"></el-input>
                </template>
              </el-table-column>
            </el-table>
            <el-row style="position: absolute; left: calc(50% + 20px); top: 100px;">
              <el-button icon="el-icon-sort" circle style="transform: rotate(90deg); " type="success"  title="互换" @click="exchange">
              </el-button>
            </el-row>
          </el-col>
          <el-col :span="24">
            <el-row type="flex" justify="center" style="margin-top:10px;">
              <!-- :disabled="valueMapper.synoId" -->
              <synonym ref="synonymTree" @synonymClick="synonymClick"></synonym>
<!--              <dir-tree ref="driTree" :moduleUrl="moduleUrl" keyLabel="stdName" :id="valueMapper.synoId" v-model="valueMapper.stdName" @node-click="nodeClickHandle"></dir-tree>-->
              <dict-select ref="dictSelect" style="margin-left: 20px;" :id="valueMapper.dictId" v-model="valueMapper.dictName" @node-click="currentChangeHandle"></dict-select>
              <el-button style="margin-top: 0; margin-left: 20px; width: 200px;" class="el-table-add-row" @click="addObj" icon="el-icon-plus"> 添加</el-button>
            </el-row>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <div class="el-dialog__footer">
      <span class="dialog-footer">
         <el-button
           icon="el-icon-back"
           @click="cancel">取消
            </el-button>
            <el-button
              type="primary" icon="el-icon-check"
              @click="handleSaveData()">确定
           </el-button>
      </span>
    </div>
  </div>
</template>

<script>
  /* eslint-disable new-cap */
  import API from '../../../../../api/index'
  import mxgraph from '../../../../../graph/VueMxGraphLoader'
  import dictSelect from '../../../std/dict-select.vue'
  import synonym from './synonym'

  const {
    mxUtils,
    mxCodec
  } = mxgraph
  export default {
    name: 'valueMapper',
    props: {
      name: String
    },
    components: {
      dictSelect,
      synonym
    },
    data () {
      return {
        moduleUrl: 'std/syno/type/',
        graph: null,
        valueMapper: {
          name: '',
          field_to_use: '',
          target_field: '',
          non_match_default: '',
          fields: [],
          dictName: '',
          dictId: '',
          // 权威名称
          stdName: '',
          synoId: ''
        },
        temp: {
          name: '',
          field_to_use: '',
          target_field: '',
          non_match_default: '',
          fields: [],
          dictName: '',
          dictId: '',
          // 权威名称
          stdName: '',
          synoId: ''
        },
        fieldOptions: [],
        dataListLoading: false
      }
    },
    mounted () {

    },
    methods: {
      loadData (data) {
        if (data) {
          this.$forceUpdate()
          this.$deepCopy(this.valueMapper, data)
          console.log(this.valueMapper)
          if (this.valueMapper.synoId && this.valueMapper.synoId !== 'null') {
            console.log(this.valueMapper.stdName)
          }
          // if (this.valueMapper.dictId && this.valueMapper.dictId !== 'null') {
          //   this.$nextTick(() => {
          //     this.$refs.dictSelect.init(this.valueMapper.dictId)
          //   })
          // } else {
          //   this.$nextTick(() => {
          //     this.$refs.dictSelect.init()
          //   })
          // }
        }
      },
      // 保存表单数据
      handleSaveData () {
        if (this.valueMapper.name) {
          this.$emit('savePluginData', this.valueMapper)
        } else {
          this.$message({
            message: '步骤名称必填',
            type: 'warning'
          })
        }
      },
      setGraph (val) {
        this.graph = val
        this.getStreamField()
      },
      cancel () {
        this.$emit('cancel')
      },
      // 重置表单数据
      resetFormData (stepname) {
        this.$forceUpdate()
        this.$refs['valueMapper'].resetFields()
        this.$deepCopy(this.valueMapper, this.temp)
        // this.valueMapper = JSON.parse(JSON.stringify(this.temp))
        this.valueMapper['name'] = stepname
      },
      async getStreamField () {
        const value = await this.getXml()
        await API.trans.inputFields(value, {'stepName': this.valueMapper.name}).then(res => {
          this.$set(this, 'fieldOptions', res.data)
        })
      },
      getXml () {
        this.saveTempPluginData(this.valueMapper)
        const graph = this.graph
        const enc = new mxCodec(mxUtils.createXmlDocument())
        const node = enc.encode(graph.getModel())
        const value = mxUtils.getPrettyXml(node)
        return value
      },
      saveTempPluginData (formData) {
        this.$emit('saveTempPluginData', formData)
      },
      removeObj (index) {
        this.valueMapper.fields.splice(index, 1)
      },
      addObj () {
        this.valueMapper.fields.push({})
        this.$nextTick(() => {
          let container = this.$el.querySelector('.el-table__body-wrapper')
          container.scrollTop = container.scrollHeight
        })
      },
      currentChangeHandle (data, node) {
        if (!data) {
          this.valueMapper.dictName = ''
          this.valueMapper.dictId = ''
          this.valueMapper.fields = []
          return
        }
        const _that = this
        _that.valueMapper.synoId = ''
        _that.dataListLoading = true
        _that.valueMapper.dictName = data.dictName
        _that.valueMapper.dictId = data.id
        _that.$http({
          url: this.$http.adornUrl(`/std/dict/type/${data.id}`),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            _that.valueMapper.fields.length = 0
            for (var i = 0; i < data.dict.length; i++) {
              var row = {}
              row.source_value = data.dict[i].dictCode
              row.target_value = data.dict[i].dictName
              _that.valueMapper.fields.push(row)
            }
          }
          this.dataListLoading = false
        })
      },
      synonymClick (nodeList) {
        // 防止重复
        let map = {}
        for (let item of this.valueMapper.fields) {
          map[item.source_value] = true
        }
        for (let item of nodeList) {
          if (!map.hasOwnProperty(item.synoName)) {
            this.valueMapper.fields.push({source_value: item.synoName, target_value: item.stdName})
          }
        }
      },
      exchange () {
        for (var i in this.valueMapper.fields) {
          const tmp = this.valueMapper.fields[i].source_value
          this.valueMapper.fields[i].source_value = this.valueMapper.fields[i].target_value
          this.valueMapper.fields[i].target_value = tmp
        }
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">

.box{
  position:relative;
  border:1px solid #dcdfe6;
  padding:30px 5px 10px 5px;
}
.box::before{
  content:attr(title);
  position:absolute;
  top: 0%;
  left:10%;
  transform:translateX(-50%);
  -webkit-transform:translate(-50%,-50%);
  padding:0px 10px;
  background-color:#fff;
}
</style>
